'use strict';
const Controller = require('egg').Controller;
const news = [{
        id: 1,
        name: "第一条新闻",
        tiem_d: "2020-12-25"
    },
    {
        id: 2,
        name: "第二条新闻",
        tiem_d: "2020-12-25"
    },
    {
        id: 3,
        name: "第三条新闻",
        tiem_d: "2020-12-25"
    },
    {
        id: 4,
        name: "老虎吃人",
        tiem_d: "2020-12-25"
    }
]

class NewsController extends Controller {
    async index() {
        const {ctx,app} = this;
        const {keyname} = ctx.request.query
        let where = "";
        if(keyname){
            where = `where title like "%${keyname}%"`
        }
        const result = await app.mysql.query(`select * from hcy_news ${where}`)
        ctx.body = {
            code: 0,
            msg: '请求成功',
            data: result
        };
    }
    async show() {
        const {ctx,app} = this;
        const {id} = ctx.params;
        console.log();
        const data = news.find(item => item.id === +id)
        ctx.body = {
            code: 0,
            data,
            msg: "查询成功",
        };
    }
    async create() {
        const {ctx} = this;
        const {name,tiem_d} = ctx.request.body
        if (name) {
            news.push({
                id: name,
                tiem_d
            })
            ctx.body = {
                code: 0,
                msg: "新增成功",
            };
        } else {
            ctx.body = {
                code: 40006,
                msg: "缺少必要参数",
            };
        }
    }
    async update() {
        const {ctx} = this;
        const { name,tiem_d
        } = ctx.request.body
        const {id} = ctx.params
        if (name) {
            const index = news.findIndex(item => item.id === +id)
            news[index].name = name
            news[index].tiem_d = tiem_d
            ctx.body = {
                code: 0,
                msg: "编辑成功",
            };
        } else {
            ctx.body = {
                code: 40006,
                msg: "缺少必要参数",
            };
        }
    }
    async destroy() {
        const {
            ctx
        } = this;
        ctx.body = 'hi, del';
    }
}

module.exports = NewsController;